Decimal To Hexadecimal Algorithm
The Decimal to Hexadecimal Algorithm is a widely used method for converting decimal (base-10) numbers into hexadecimal (base-16) representation. This process is widely used in computer science and mathematics, as it allows for easier representation and manipulation of large numbers, particularly those related to memory addresses, color codes, and other digital data. Hexadecimal numbers use a set of 16 distinct symbols, including 0-9 for the first ten digits and A-F for the next six, which represent values 10-15. The algorithm converts a decimal number to its equivalent hexadecimal value by repeatedly dividing the decimal number by 16 and keeping track of the remainders, which eventually form the hexadecimal representation of the input number.
To execute the Decimal to Hexadecimal Algorithm, one starts by dividing the given decimal number by 16, then records the remainder and quotient. The remainder corresponds to the least significant digit in the hexadecimal representation, while the quotient is used for the next iteration of the process. This procedure is repeated until the quotient becomes zero, at which point the remainders collected in reverse order form the final hexadecimal representation. For example, if the input decimal number is 255, the first division would yield a quotient of 15 and a remainder of 15 (corresponding to the hexadecimal digit F). The next division would result in a quotient of 0 and a remainder of 15 (another F). As the quotient is now 0, the algorithm stops, and the hexadecimal representation is obtained by reading the remainders in reverse order: FF.
#include <iostream>
using namespace std;
int main(void)
{
int valueToConvert = 0; //Holds user input
int hexArray[8]; //Contains hex values backwards
int i = 0; //counter
char HexValues[] = "0123456789ABCDEF";
cout << "Enter a Decimal Value" << endl; //Displays request to stdout
cin >> valueToConvert; //Stores value into valueToConvert via user input
while (valueToConvert > 15)
{ //Dec to Hex Algorithm
hexArray[i++] = valueToConvert % 16; //Gets remainder
valueToConvert /= 16;
}
hexArray[i] = valueToConvert; //Gets last value
cout << "Hex Value: ";
while (i >= 0)
cout << HexValues[hexArray[i--]];
cout << endl;
return 0;
}